package com.hhuhh.smarthome.socket.support;

import java.nio.charset.Charset;

import org.apache.mina.core.buffer.IoBuffer;
import org.apache.mina.core.session.IoSession;
import org.apache.mina.filter.codec.ProtocolEncoderAdapter;
import org.apache.mina.filter.codec.ProtocolEncoderOutput;
import org.apache.mina.filter.codec.textline.LineDelimiter;

public class ByteEncoder extends ProtocolEncoderAdapter {
	
	private final static Charset charset = Charset.forName("UTF-8");

	@Override
	public void encode(IoSession session, Object message,
			ProtocolEncoderOutput out) throws Exception {
		
        IoBuffer buff = IoBuffer.allocate(64).setAutoExpand(true);

        if(message instanceof String){
        	buff.putString(message.toString(), charset.newEncoder());
        }
        
        if(message instanceof byte[]){
        	buff.put((byte[]) message);
        }
        
        // put 当前系统默认换行符

        buff.putString(LineDelimiter.CRLF.getValue(), charset.newEncoder());

        // 为下一次读取数据做准备
        buff.flip();

        out.write(buff);
		
	}

}
